package com.gohi.main.wxapi.util;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.dom4j.Branch;

import com.gohi.main.util.StringUtil;

import com.gohi.main.wxapi.vo.JsApi;
import com.gohi.main.wxapi.vo.Token;
import com.gohi.main.wxapi.vo.WxAccount;
import com.gohi.main.wxpay.api.WxPayUtil;

public class AccoutUtil {
	public static Logger logger = Logger.getLogger(AccoutUtil.class);
	public static List<WxAccount> alist;

	// 获取单个账户 每次调用前 记得刷新一下
	public static WxAccount getAccount() {
		WxAccount acc = WxPayUtil.getAccount();
		if (acc == null) {
			// 没有初始化
			acc = RefAccount();
			WxPayUtil.setAccount(acc);
		} else if (acc.getLasttime() == 0
				|| StringUtil.getTimeSimple() - acc.getLasttime() > 6100) {
			acc = RefAccount();
			WxPayUtil.setAccount(acc);
			
		}
		return acc;
	}

	// 刷新指定的account
	public static WxAccount RefAccount() {
		WxAccount w = new WxAccount();
		Token t = null;
		for (int i = 0; i < 10; i++) {
			logger.info("开始刷新access_token:"+i);
			t = com.gohi.main.wxapi.process.WxApi.getToken(WxPayUtil.WX_APPID,
					WxPayUtil.WXAppSecret);
			if (t != null) {
				logger.info("刷新access_token");
				break;
			}
		}
		if(t==null){
			logger.error("刷新access_token失败啦！");
		}
		// 设置
		w.setAccess_token(t.getAccessToken());
		w.setToken_time(t.getExpiresIn() + "");
		w.setJsapi(t.getJsapiTicket());
		w.setJs_time(t.getExpiresIn());
		w.setLasttime(StringUtil.getTimeSimple());
		WxPayUtil.setAccount(w);

		return w;
	}

	/**
	 * 根据ID 获取 Account
	 * 
	 * @param id
	 * @return
	 */
	public static WxAccount getAccountByid() {
		return getAccount();
	}

	/**
	 * 网页授权JS代码
	 * 
	 * @param id
	 * @return
	 */
	public static JsApi getJsApiByid(String id, String url) {
		JsApi js = null;
		js = WxJsSign.sign(getAccount().getJsapi(), url);
		js.setAppid(WxPayUtil.WX_APPID);// 设置APPID

		return js;
	}

	public static void initlist(List<WxAccount> list) {
	}

	public static List<WxAccount> getAlist() {
		return alist;
	}

	public static void setAlist(List<WxAccount> alist) {
		// System.err.println("初始化完毕");
		AccoutUtil.alist = alist;
	}

}
